import { useUserStore } from "@/store"
const userStore = useUserStore()

const baseURL = ''
export const http = {
    request: (options: any) => {
      return new Promise((resolve, reject) => {
        uni.request({
            url: baseURL + options.url,
            method: options.method || 'GET',
            params: options.params || {},
            data: options.data || {},
            header: {
                'openid': userStore.openid,
                'role': userStore.role,
            },
            success: (res) => {
                resolve(res.data)
            },
            fail: (err) => {
                reject(err)
            }
        })
      })  
    },
    get: (url: string, params?: any) => {
        return new Promise((resolve, reject) => {
            http.request({
                url: url,
                method: 'GET',
                params: params
            }).then(res => {
                if (res.code === 200) {
                    resolve(res)
                    return
                }
                
                uni.showToast({
                    title: res.msg || '请求错误',
                    icon: 'none'
                })
                reject(res)
            }).catch(err => {
                uni.showToast({
                    title: err.msg || '请求错误',
                    icon: 'none'
                })
                reject(err)
            })
        })
      
    },
    post: (url: string, params?: any) => {
        return new Promise((resolve, reject) => {
            http.request({
                url: url,
                method: 'POST',
                data: params
            }).then(res => { 
                resolve(res)
            }).catch(err => {
                uni.showToast({
                    title: err.msg || '请求错误',
                    icon: 'none'
                })
                reject(err)
            })    
        })
    }
}